home *** CD-ROM | disk | FTP | other *** search
- Path: druid.borland.com!usenet
- From: pete@borland.com (Pete Becker)
- Newsgroups: comp.lang.c++
- Subject: Re: Aborting Constructors, Part II
- Date: 6 Feb 1996 20:57:03 GMT
- Organization: Borland International
- Message-ID: <4f8fav$kik@druid.borland.com>
- References: <4eoeck$t6n@news.ios.com>
- NNTP-Posting-Host: pbecker.borland.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=ISO-8859-1
- X-Newsreader: WinVN 0.99.5
-
- In article <4eoeck$t6n@news.ios.com>, leonardj@tribeca.ios.com says...
- >
- >
- > Earlier, I posted a message about aborting a constructor if for some
- >reason some resource cannot be allocated. I did some thinking about
- >the problem and I thought, why couldn't you just call 'delete' inside
- >of the constructor itself and then let the destructor take care of the
- >release of all resources allocated so far. To find out whether or not
- >this would work, I wrote the following test program, compiled and ran
- >it under BC++ 4.52. It produced the output at the bottom of the page:
- >
- >// File: abort constructor test
- >
- >#include <iostream.h>
- >#include <except.h>
- >#include <cstring.h>
- >
- >class test{
- > public:
- > test();
- > ~test();
- >};
- >
- >test::test(){
- > cout << "constructing object\n";
- > delete this;
- > throw(xmsg(string("deleted the object!\n")));
- >}
- >
- >test::~test(){
- > cout << "deleting object\n";
- >}
- >
- >void main(){
- >
- > try{
- > test *at = new test;
- > }
- >
- > catch(xmsg error){
- > cout << error.why();
- > }
- >}
- >
- > When compiled and run this produces the following output:
- >
- >constructing object
- >deleting object
- >deleted the object!
- >
- > I'm guessing from this result that this is a valid way to do this. If
- >you have any opinion on this, especially if you happen to know of a
- >reason why this is not good, or conflicts somehow with what is
- >considered good C++ programming practice, I would like to know.
- > Thanks
- >
-
- Now try this variant of your program:
-
- int main()
- {
- test t;
- return 0;
- }
-
- Be prepared to reboot. No, the problem is not that there is no try block in
- main.
- -- Pete
-
-